package com.donfu.web.controller.wxhouse;

import com.donfu.common.core.controller.BaseController;
import com.donfu.common.core.domain.AjaxResult;
import com.donfu.common.core.page.TableDataInfo;
import com.donfu.system.domain.house.*;
import com.donfu.system.service.house.*;
import com.donfu.web.controller.tool.MapHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺的微信端管理
 */
@Api(tags = "前台-微信店铺接口管理")
@RestController
@RequestMapping("/wx/houseStore")
public class WebHouseStoreController extends BaseController {

    @Autowired
    private IHouseStoreService houseStoreService;

    @Autowired
    private IHouseShoppersService houseShoppersService;

    @Autowired
    private IHouseExclusiveserviceService houseExclusiveserviceService;

    @Autowired
    private IHouseStoreArticleService houseStoreArticleService;

    @Autowired
    private IHouseRegionService houseRegionService;

    /**
     * 查询店铺内的文章列表
     */
    @ApiOperation("查询店铺内文章列表")
    @GetMapping("/listArticle")
    public TableDataInfo list(HouseStoreArticle houseStoreArticle)
    {
        startPage();
        List<HouseStoreArticle> list = houseStoreArticleService.selectHouseStoreArticleList(houseStoreArticle);
        return getDataTable(list);
    }

    /**
     * 获取店铺内的文章详细信息
     */
    @ApiOperation("获取文章详情")
    @GetMapping(value = "/article/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(houseStoreArticleService.selectHouseStoreArticleById(id));
    }

    /**
     * 根据城市Id查询所在的店铺
     * @param cityId
     * @return
     */
    @ApiOperation("根据城市Id查询城市店铺")
    @GetMapping("/listByCityId")
    public TableDataInfo getListByCity(@RequestParam(required = false,defaultValue = "") String cityId,@RequestParam(required = false) String du){
        startPage();
        HouseStore store=new HouseStore();
        store.setCity(cityId);
        List<HouseStore> list = houseStoreService.selectHouseStoreList(store);
        if(list!=null && list.size()>0){
            // 对当前列表进行排序，根据距离的大小
            List<HouseStore> houseStoreList = list.stream().
                    // 利用map方法进行计算，算出距离
                            map(houseStore -> {
                        houseStore.setDistance(MapHelper.GetPointDistance(du, houseStore.getLatitude() + "," + houseStore.getLongitude()));
                        return houseStore;
                    }).sorted((o1, o2) ->
                            // 根据距离升序
                            (int) Math.round(o1.getDistance() - o2.getDistance())
                    ).collect(Collectors.toList());
            TableDataInfo dataTable = getDataTable(houseStoreList);
            // 获取数据总条数
            int i = houseStoreService.selectHouseStoreCount(cityId);
            dataTable.setTotal(i);
            return dataTable;
        }
        return getDataTable(list);
    }

    /**
     * 距离你当前位置最近的一家店铺
     * @param du 纬经度
     * @return
     */
    @ApiOperation("获取距离你最近的一家店铺")
    @GetMapping("/getStoreByDistance")
    public AjaxResult getStoreB(@RequestParam(required = false) String du){

        List<HouseStore> list = houseStoreService.selectHouseStoreList(null);
        if(list!=null && list.size()>0) {
            // 对当前列表进行排序，根据距离的大小
            List<HouseStore> houseStoreList = list.stream().
                    // 利用map方法进行计算，算出距离
                            map(houseStore -> {
                        houseStore.setDistance(MapHelper.GetPointDistance(du, houseStore.getLatitude() + "," + houseStore.getLongitude()));
                        return houseStore;
                    }).sorted((o1, o2) ->
                            // 根据距离升序
                            (int) Math.round(o1.getDistance() - o2.getDistance())
                    ).collect(Collectors.toList());

            return AjaxResult.success(houseStoreList.get(0));
        }
        return AjaxResult.success();
    }

    /**
     * 查询店铺所在的地址的列表
     * @return
     */
    @ApiOperation("获取所有店铺所在城市所组成的列表")
    @GetMapping("/getCityList")
    public AjaxResult getCityList(){
        List<Map<String,String>> citys= houseStoreService.selectHouseStoreCityList();
        return AjaxResult.success(citys);
    }

    @ApiOperation("获取店铺详情")
    @GetMapping("/storeById")
    public AjaxResult getStoreByStoreId(Long id,@RequestParam(required = false) String du){
        HouseStore store = houseStoreService.selectHouseStoreById(id);
        Double distance = MapHelper.GetPointDistance(store.getLatitude() + "," + store.getLongitude(), du);
        store.setDistance(distance);
        return AjaxResult.success(store);
    }

    /**
     * 根据店铺id，用户id查找列表
     * @param storeId
     * @param
     * @return
     */
    @ApiOperation("根据店铺id，用户id查找导购列表")
    @GetMapping("/getShopperList")
    public AjaxResult getShopperByStoreId(Long storeId,Long userId){

        //  1、根据店铺id，用户id查询我的导购表，如果有数据，则直接返回数据
        HouseExclusiveservice houseExclusiveservice=new HouseExclusiveservice();
        houseExclusiveservice.setUserId(userId);
        houseExclusiveservice.setStoreId(storeId);
        List<HouseShoppers> shoppersList =new ArrayList<>();
        AjaxResult ajaxResult = AjaxResult.success();
        List<HouseExclusiveservice> houseExclusiveserviceList = houseExclusiveserviceService.selectHouseExclusiveserviceList(houseExclusiveservice);
        if(houseExclusiveserviceList!=null && houseExclusiveserviceList.size()>0){
            // 查询导购的信息
            HouseShoppers houseShoppers = houseShoppersService.selectHouseShoppersById(houseExclusiveserviceList.get(0).getShopperId());
            shoppersList.add(houseShoppers);
            ajaxResult.put("isPrivateShopper",1);
            ajaxResult.put("data",shoppersList);
            return ajaxResult ;
        }
        // 2、如果我的导购表里没有数据，则查询店铺导购表，返回相关数据
        shoppersList = houseShoppersService.selectHouseShoppersListByStoreId(storeId);
        ajaxResult.put("isPrivateShopper",0);
        ajaxResult.put("data",shoppersList);
        return ajaxResult;
    }

    /**
     * 查询导购的详细信息
     * @param shopperId
     * @return
     */
    @ApiOperation("根据导购Id查询详细信息")
    @GetMapping("/getShopperInfo/{shopperId}")
    public AjaxResult getShopperInfoByShopperId(@PathVariable("shopperId") Long shopperId){
        return AjaxResult.success(houseShoppersService.selectHouseShoppersById(shopperId));
    }

    /**
     * 绑定导购
     * @param userId 用户id
     * @param storeId 店铺id
     * @param shopperId 导购id
     * @param userName 用户名称
     * @return
     */
    @ApiOperation(("绑定导购"))
    @PostMapping("/addExclusive")
    public AjaxResult addExclusive(@RequestParam("userId") Long userId,
                                   @RequestParam("storeId") Long storeId,
                                   @RequestParam("shopperId") Long shopperId,
                                   @RequestParam("userName") String userName){
        HouseExclusiveservice exclusiveservice=new HouseExclusiveservice();
        exclusiveservice.setUserId(userId);
        exclusiveservice.setStoreId(storeId);
        exclusiveservice.setShopperId(shopperId);
        exclusiveservice.setUserName(userName);
        String storeName = houseStoreService.selectHouseStoreById(storeId).getName();
        String shopperName = houseShoppersService.selectHouseShoppersById(shopperId).getName();
        exclusiveservice.setStoreName(storeName);
        exclusiveservice.setShopperName(shopperName);
        int i = houseExclusiveserviceService.insertHouseExclusiveservice(exclusiveservice);
        return toAjax(i);
    }

    /**
     * 解除绑定
     * @param shopperId
     * @return
     */
    @ApiOperation("根据用户id,店铺id解除导购绑定")
    @DeleteMapping
    public AjaxResult deleteShopperByShopperId(Long shopperId){
        Long userId=null;
        int i=houseExclusiveserviceService.deleteHouseExclusiveserviceByShopperIdAndUserId(userId,shopperId);
        return toAjax(i);
    }

    /**
     * 获取行政区域
     * @return
     */
    @ApiOperation("获取行政区域")
    @GetMapping("/getRegionList")
    public AjaxResult getRegion(){
        List<HouseRegion> houseRegionAllList = new ArrayList<>();

        //所有数据
        List<HouseRegion> houseRegionList = houseRegionService.selectHouseRegionList(new HouseRegion());
        //根据级别分组，级别的值作为键名
        Map<Integer, List<HouseRegion>> collect = houseRegionList.stream().collect(Collectors.groupingBy(HouseRegion::getType));

        Integer provinceType = 1;
        //根据分类的值省级数据
        List<HouseRegion> provinceList = collect.get(provinceType);

        Integer cityType = 2;
        //市级数据
        List<HouseRegion> city = collect.get(cityType);
        // 根据父类id分组，也就是根据省级id分组
        Map<Long, List<HouseRegion>> cityListMap = city.stream().collect(Collectors.groupingBy(HouseRegion::getPid));

        Integer areaType = 3;
        //县级数据
        List<HouseRegion> areas = collect.get(areaType);
        // 根据父类id分组，也就是根据市级id分组
        Map<Long, List<HouseRegion>> areaListMap = areas.stream().collect(Collectors.groupingBy(HouseRegion::getPid));

        for (int i = 0; i < provinceList.size(); i++) {
            HouseRegion province = provinceList.get(i);

            // 从市级数据中查询出父类ID是当前省份的数据的集合
            List<HouseRegion> cityList = cityListMap.get(province.getId());
            List<HouseRegion> cityVOList = new ArrayList<>();
            // 循环遍历当前市级的集合，将区级数据注入到相应的市级对象中
            for (int j = 0; j <cityList.size() ; j++) {
                HouseRegion cityRegion = cityList.get(j);

                List<HouseRegion> areaList = areaListMap.get(cityRegion.getId());
                //List<HouseRegion> areaVOList = new ArrayList<>();
                //for (int k = 0; k <areaList.size() ; k++) {
                //    HouseRegion areaRegion = areaList.get(k);
                //    areaVOList.add(areaRegion);
                //}

                // 获取市下面的区域的集合
                cityRegion.setChildren(areaList);
                // 将市集合放到省的集合中
                cityVOList.add(cityRegion);

            }
            province.setChildren(cityVOList);
            houseRegionAllList.add(province);
        }

        return  AjaxResult.success(houseRegionAllList);
    }


}
